package cc.chengheng.security.springmvc.interceptor;

import cc.chengheng.security.springmvc.model.UserDto;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class SimpleAuthenticationInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        response.setHeader("content-type", "text/html;charset=utf-8");

        // 处理url资源访问权限

        Object object = request.getSession().getAttribute(UserDto.SESSION_USER_KEY);

        if (object == null) {
            response.getWriter().write("请登录");
        }

        UserDto userDto = (UserDto) object;

        String requestURI = request.getRequestURI();

        if (userDto.getAuthorities().contains("p1") && requestURI.contains("p1")) {
            return true;
        }

        if (userDto.getAuthorities().contains("p1") && requestURI.contains("p2")) {
            return true;
        }

        response.getWriter().write("没有权限,拒绝访问");

        return false;
    }
}
